<?php

namespace App\Models\Admin;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Model;
use Config;
use App\Common\ValidateHandler;
use DB;

class Grade extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'level', 'title',
        'describe', 'icon', 'type', 'bc_img', 
        'color_first', 'color_second', 'jf_num', 'recommend', 
        'created_at', 'updated_at'
    ];
    // 获取会员等级信息 - 传递店铺ID 
    public function getGradeText($id)
    {
        $arr = [];
        $arr['data'] = [];
        $arr['num'] = 0;
        $grade = $this->where('store_id', $id)->orderBy('level')->get()->toArray();
        $arr['grade'] = $grade;
        $arr['num'] = count($grade);
        foreach ($grade as $key => $val) {
            $arr['data'][$val['level']]['store_id'] = $val['store_id'];
            $arr['data'][$val['level']]['level'] = $val['level'];
            $arr['data'][$val['level']]['title'] = $val['title'];
            $arr['data'][$val['level']]['describe'] = $val['describe'];
            $arr['data'][$val['level']]['type'] = $val['type'];
            $typeAll = $this->typeText($val);
            $arr['data'][$val['level']]['type_text'] = $typeAll['text'];
            $arr['data'][$val['level']]['type_content'] = $typeAll['content'];
            $arr['data'][$val['level']]['buy'] = '历史订单零售价达 '.$val['jf_num'].' 元';
            $recommend = json_decode($val['recommend'], 1);
            $arr['data'][$val['level']]['refer'] = '需要推荐 '.$recommend['num'].' 名 '.$grade[$recommend['grade']]['title'];
            $arr['data'][$val['level']]['created_at'] = $val['created_at'];
        }
        return $arr;
    }
    public function typeText($val)
    {
        $arr = [];
        switch ($val['type']) {
            case 1:
                # 图片
                $arr['text'] = '背景图片';
                $arr['content'] = $val['bc_img'];
                break;
            case 2:
                # 渐变色
                $arr['text'] = '渐变色';
                $arr['content'] = $val['color_first'].' => '.$val['color_second'];
                break;
            default:
                # code...
                break;
        }
        return $arr;
    }
    // 通过ID 获取店铺的 会员等级 和 会员名字信息
    public function gradeOptions($id)
    {
        $option = [];
        $gradeNum = $this->where('store_id',$id)->orderBy('level')->get()->toArray();
        foreach ($gradeNum as $key => $val) {
            $option[$val['level']]['value'] = $val['level'];
            $option[$val['level']]['label'] = $val['title'];
        }
        return $option;
    }

    // 通过ID 获取对应店铺会员数目
    public function gradeNum($id)
    {
        return $gradeNum = $this->where('store_id',$id)->count();
    }

    // 通过ID 获取对应店铺的等级信息
    public function getGrade($id)
    {
        return $info_grade = $this->where('store_id',$id)->orderBy('level')->get()->toArray();
    }

    // 验证 店铺id是否合法 / 验证店铺是否存在 / 获取店铺信息
    public function validateGrade($id)
    {
        // 判断 店铺ID 是否存在
        if (empty($id) || $id === 0) {
            return $this->error(['info' => '店铺ID 不合法!']);
        }
        // 判断 店铺信息 是否存在
        $Store = new Store;
        $store_info = $Store->findStore($id);
        if (empty($store_info)) {
            return $this->error(['info' => '['.$id.']店铺不存在!请先添加店铺!']);
        }
        $store_garde = $this->getGrade($id);
        return $this->success(['data' => $store_garde, 'info' => '['.$id.']店铺会员等级信息验证成功!']);
    }

    // 初始化指定店铺 的 等级信息
    public function analyGrade($id)
    {
        // 判断 店铺等级信息 是否存在 => 如果不存在 , 初始化数据 ,否则 调用分析函数
        $analy = [];
        $grade = [];
        $validate_grade = $this->validateGrade($id);
        if($validate_grade['code'] !== 20000){
            return $validate_grade;
        }else{
            $store_garde = $validate_grade['data']['data'];
        }
        if (empty($store_garde)) {
            // 等级(同时也是数组长度) / 等级名字 / 等级购买要求(必填 默认0元) / 等级推荐要求(选填 默认空) / 等级描述 / 等级图标 / 等级等级卡方案(1-渐变色 / 2-背景图片)
            $analy[0]['store_id'] = $id;
            $analy[0]['level'] = 0;
            $analy[0]['title'] = '会员';
            $analy[0]['jf_num'] = 0;// 必填 默认0元
            $analy[0]['jf'] = 0;// 必填 默认0元
            $analy[0]['recommend'] = ['num' => 0 , 'grade' => 0 ];// 选填 默认为空 / 非空格式为 : ['num' => 0 , 'grade' => 0 ]
            $analy[0]['describe'] = '';
            $analy[0]['icon'] = '';

            $analy[0]['copartner'] = 0;
            $analy[0]['direct_num'] = 0;
            $analy[0]['team_num'] = 0;
            $analy[0]['team_sales'] = 0;

            // 需要重新变成四字段数据 , 但是 cardIni 保持
            $analy[0]['type'] = 2;
            $analy[0]['color_first'] = '#cba071';
            $analy[0]['color_second'] = '#e1bf83';
            $analy[0]['bc_img'] = '';
        
            $analy[0]['cardIni'] = ['type'=>2, 'color_first'=>'#cba071', 'color_second'=>'#e1bf83', 'bc_img' => ''];

            $grade[0]['value'] = 0;
            $grade[0]['label'] = '会员';
        }else{
            $data = $this->getAnlayArr($store_garde);
            $analy = $data['analy'];
            $grade = $data['grade'];
        }
        $icon = Config::get("const.icon_arr");
        return $this->success(['data' => $analy, 'grade' => $grade, 'iconArr' => $icon, 'info' => '['.$id.']店铺会员等级信息解析成功!']);
    }

    // 数据格式分析函数(读取) - 数据库的店铺会员等级信息
    public function getAnlayArr($store_garde)
    {
        $info = [];
        $analy = [];
        $grade = [];
        foreach ($store_garde as $key => $val) {
            $card = ['type' => $val['type'], 'color_first' => $val['color_first'],'color_second' => $val['color_second'], 'bc_img' => $val['bc_img']];// 获取指定格式的卡牌背景样式
            $analy[$val['level']]['store_id'] = $val['store_id'];
            $analy[$val['level']]['level'] = $val['level'];
            $analy[$val['level']]['title'] = $val['title'];
            $analy[$val['level']]['jf_num'] = $val['jf_num']/100;
            $analy[$val['level']]['jf'] = $val['jf']/100;
            $analy[$val['level']]['recommend'] = !$val['recommend'] ? ['num' => 0 , 'grade' => 0 ] : json_decode($val['recommend']);
            $analy[$val['level']]['describe'] = $val['describe'];
            $analy[$val['level']]['icon'] = $val['icon'];

            $analy[$val['level']]['copartner'] = $val['copartner'];
            $analy[$val['level']]['direct_num'] = $val['direct_num'];
            $analy[$val['level']]['team_num'] = $val['team_num'];
            $analy[$val['level']]['team_sales'] = $val['team_sales']/100;

            $analy[$val['level']]['type'] = $val['type'];
            $analy[$val['level']]['color_first'] = $val['color_first'];
            $analy[$val['level']]['color_second'] = $val['color_second'];
            $analy[$val['level']]['bc_img'] = $val['bc_img'];

            $analy[$val['level']]['cardIni'] = $card;
            
            $grade[$val['level']]['value'] = $val['level'];
            $grade[$val['level']]['label'] = $val['title'];
        }
        $info['analy'] = $analy;
        $info['grade'] = $grade;
        return $info;
    }
    
    // 数据格式分析函数(插入) - 前台提交的数据
    public function insertAnlayArr($id, $data)
    {
        $is_first = false; // 是否是初次 = false ( 默认不是初次 , 需要 删除 并 插入 )
        $insert_data = false; // 默认尚未插入成功
        $del_data = false; // 默认尚未删除成功

        $validate_grade = $this->validateGrade($id);
        if ($validate_grade['code'] != 20000) {
            return $validate_grade;
        } else {
            $garde_info = $validate_grade['data']['data'];
        }
        // 初次插入 , 无需删除所以默认删除成功
        if (empty($garde_info)) {
            $is_first = true;
            $del_data = true;
        }
        $insert_grade = $this->foreachGet($data, $id);
        if ($insert_grade['code'] != 20000) {
            return $insert_grade;
        }
        DB::beginTransaction();
        try {       
            // 不是初次插入 , 需要删除数据
            if ($is_first === false) {
                $del_data = $this->where('store_id', $id)->delete();// 删除此店铺信息
            }
            if ($del_data) {
                $insert_data = $this->insert($insert_grade['data']['data']);
            } else {
                return $this->error(['info' => '店铺等级信息添加前的数据清空失败!请重试!']);
            }
            if ($insert_data && $del_data) {
                DB::commit();
                return $this->success(['info' => '店铺等级信息添加成功!']);
            } else {
                return $this->error(['info' => '店铺等级信息添加失败!请重试!']);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }

    // 遍历前台数据 形成插入的内容
    public function foreachGet($data, $id)
    {
        $insert = [];
        foreach ($data as $key => $val) {
            $data = $this->validate($val);
            if (!$data['res']) {
                return $this->error(['info' => $data['info']]);
            }
            $insert[$val['level']]['store_id'] = $id;
            $insert[$val['level']]['level'] = $val['level'];
            $insert[$val['level']]['title'] = $val['title'];
            $insert[$val['level']]['jf_num'] = $val['jf_num']*100;
            $insert[$val['level']]['jf'] = $val['jf']*100;
            $insert[$val['level']]['recommend'] = !$val['recommend'] ? '{"grade":0,"num":0}' : '{"grade":'.$val['recommend']['grade'].',"num":'.$val['recommend']['num'].'}';
            $insert[$val['level']]['describe'] = $val['describe'] ? $val['describe'] : '';
            $insert[$val['level']]['icon'] = $val['icon'] ? $val['icon'] : '';

            $insert[$val['level']]['type'] = $val['type'];
            $insert[$val['level']]['color_first'] = $val['color_first'] ? $val['color_first'] : '';
            $insert[$val['level']]['color_second'] = $val['color_second'] ? $val['color_second'] : '';
            $insert[$val['level']]['bc_img'] = $val['bc_img'] ? $val['bc_img'] : '';

            $insert[$val['level']]['copartner'] = $val['copartner'];
            $insert[$val['level']]['direct_num'] = isset($val['direct_num']) ? $val['direct_num'] : 0;
            $insert[$val['level']]['team_num'] = isset($val['team_num']) ? $val['team_num'] : 0;
            $insert[$val['level']]['team_sales'] = isset($val['team_sales']) ? $val['team_sales']*100 : 0;

            $insert[$val['level']]['created_at'] = date('Y-m-d H:i:s');
        }
        return $this->success(['data' =>  $insert, 'info' => '店铺等级信息分析成功!']);
    }

    //店铺会员等级表 字段合法性验证
    private function validate($data)
    {
        $arr = [
            0 => [
                'name' => '会员等级',
                'value' => $data['level'],
                'func' => 'range_num',
                'min' => 0,
                'max' => 99
            ],
            2 => [
                'name' => '会员名字',
                'value' => $data['title'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 10
            ],
            3 => [
                'name' => '购买需求',
                'value' => $data['jf_num'],
                'func' => 'range_num'
            ],
            4 => [
                'name' => '积分要求',
                'value' => $data['jf'],
                'func' => 'range_num'
            ],
            5 => [
                'name' => '等级图标',
                'value' => $data['icon'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 50
            ],
            6 => [
                'name' => '会员等级描述',
                'value' => $data['describe'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 50
            ]
        ];
        // 特殊项 : 背景卡 => type =1 背景图1-100 / type = 2 颜色1-50
        $arr = $this->cardValidate($arr, $data);
        // 选填项 : 推荐要求
        if (!empty($data->recommend) && $data->recommend !== []) {
            $arr[] = [
                'name' => '推荐要求数目',
                'value' => $data->recommend['num'],
                'func' => 'range_num',
                'min' => 0,
                'max' => 100
            ];
            $arr[] = [
                'name' => '推荐要求等级',
                'value' => $data->recommend['grade'],
                'func' => 'range_num',
                'min' => 1,
                'max' => 99
            ];
        }
        //合伙人    直推人数，团队人数，团队销售额要求
        if($data["copartner"] == 1){
            $arr[] = [
                'name' => '直推人数',
                'value' => $data['direct_num'],
                'func' => 'range_num'
            ];
            $arr[] = [
                'name' => '团队人数',
                'value' => $data['team_num'],
                'func' => 'range_num'
            ];
            $arr[] = [
                'name' => '团队销售额',
                'value' => $data['team_sales'],
                'func' => 'range_num'
            ];
        }
        return ValidateHandler::do($arr);
    }

    // 形成 验证卡牌背景字段的合法性 的数据
    public function cardValidate($arr, $data)
    {
        switch ($data['type']) {
            case 1:
                # 背景图
                $arr[] = [
                    'name' => '会员背景图',
                    'value' => $data['bc_img'],
                    'func' => 'length_limit',
                    'min' => 1,
                    'max' => 100
                ];
                break;
            case 2:
                # 渐变色
                $arr[] = [
                    'name' => '卡牌起始渐变色',
                    'value' => $data['color_first'],
                    'func' => 'length_limit',
                    'min' => 1,
                    'max' => 50
                ];
                $arr[] = [
                    'name' => '卡牌终止渐变色',
                    'value' => $data['color_second'],
                    'func' => 'length_limit',
                    'min' => 1,
                    'max' => 50
                ];
                break;
            default:
                # code...
                break;
        }
        return $arr;
    }


}
